<?php
declare (strict_types = 1);

namespace app\admin\controller\delivery\channel;

use app\common\model\delivery\CustomerGoods as GoodsModel;
use app\common\model\delivery\Goods;
use think\annotation\route\Group;
use app\admin\traits\Actions;
use think\annotation\route\Route;

#[Group("delivery/channel-customer-goods")]
class CustomerGoods extends ChannelBase
{
    use Actions{
        add as _add;
        del as _del;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsModel();
    }

    //查看
    #[Route("GET,JSON","index")]
    public function index()
    {
        $this->relationField=["area"];
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            return $this->selectpage();
        }
        $where = [];
        $where[] = ['customer_id','=',$this->request->get('customer_id')];
        [$where, $order, $limit, $with] = $this->buildparams($where);
        $list = $this->model
            ->with(['goods','spec'])
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    #[Route("GET","goodsinfo")]
    public function goodsinfo()
    {
        $goods_id=$this->request->get('goods_id');
        $goods=Goods::with(['spec'])->find($goods_id);
        $this->success('',$goods);
    }

    #[Route('GET,POST','del')]
    public function del()
    {
        $ids=$this->request->post('ids');
        $customer_id=$this->request->get('customer_id');
        GoodsModel::whereIn('id',$ids)->where('customer_id',$customer_id)->delete();
        $this->success();
    }

    #[Route('GET,POST','add')]
    public function add()
    {
        if($this->request->isPost()){
            $postdata=$this->request->post('row/a');
            GoodsModel::where(['customer_id'=>$postdata['customer_id'],'goods_id'=>$postdata['goods_id']])->delete();
            $spec=[];
            foreach($postdata['spec'] as $value){
                $spec[]=[
                    'customer_id'=>$postdata['customer_id'],
                    'goods_id'=>$value['goods_id'],
                    'spec_id'=>$value['id'],
                    'price'=>$value['price']
                ];
            }
            (new GoodsModel)->saveAll($spec);
            $this->success();
        }
        return $this->_add();
    }
}